#coding=utf-8
from twisted.internet import stdio, reactor, protocol 
from twisted.protocols import basic 
import re 
 
class DataForwardingProtocol(protocol.Protocol): 
    
	def __init__(self): 
		self.output = None

	def dataReceived(self,data):
		data = data[:-1]
		if self.output:
			if data == "login": #login
				self.login()
			if data == "cr": #choosroom
				self.chooseroom()
			if data == "sw": #sendword in the battle
				self.sendword()
			if data == "sbi": #send battle info
				self.sendbattle()
			if data == "sbr": #send battle averageresult
				self.sendbattleresult()
			if data == "lr": # leave room
				self.leaveroom()


	def login(self):
		m = "<data type='0x00'><user usrname='reynold' password='melissa'/></data>"
		print "********** <-- login to Server --> *************",m
		self.output.write(m)

	def chooseroom(self):
		m = "<data type='0x02'><choosedroom id='1'/></data>"
		print "*********** <-- Choose room to Server --> ************",m
		self.output.write(m)

	def sendword(self):
		m = "<data type='0x04'><message text='张请我吃饭'/></data>"
		print "************* <-- sendword to Server --> **********",m
		self.output.write(m)

	def sendbattle(self):
		m = "<data type='0x05'><battle><user id='1'/><move x='22o' y='330'/><angle v='45'/><power v='333'/></battle></data>"
		print "********<-- sendbattle to Server> -->**********",m
		self.output.write(m)
	
	def sendbattleresult(self):
		m = "<data type='0x07'><result><user id='1' health='46'/><user id='2' health='33'/></result></data>"
		print "*******<-- sendbattleresult to Server -->*******",m
		self.output.write(m)
		
	def leaveroom(self):
		m = "<data type='0x09'><choice v='stay'/></data>" #or quit
		print "*******<-- gameover or  stay -->*******",m
		self.output.write(m)



class StdioProxyProtocol(DataForwardingProtocol):

	def dataReceived(self,data):
		print "<< -- Server to Client -->>",data 		

	def connectionMade(self):
		inputForwarder = DataForwardingProtocol( ) 
		inputForwarder.output = self.transport 
		inputForwarder.normalizeNewlines = True 
		stdioWrapper = stdio.StandardIO(inputForwarder) 
		self.output = stdioWrapper 
 
class StdioProxyFactory(protocol.ClientFactory): 
	protocol = StdioProxyProtocol 
 
	def clientConnectionLost(self, transport, reason): 
		reactor.stop( ) 
 
	def clientConnectionFailed(self, transport, reason):
		print reason.getErrorMessage( ) 
		reactor.stop( ) 
 
if __name__ == '__main__': 
	reactor.connectTCP("127.0.0.1",5000,StdioProxyFactory()) 
	reactor.run() 
